package com.pm2.controller.plan;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.security.auth.message.callback.PrivateKeyCallback.Request;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.pm2.controller.workcalendar.WorkCalendarController;
import com.pm2.dao.WorkCalendar.WorkCalendarDao;
import com.pm2.dao.personnel.DeveloperDao;
import com.pm2.dao.plan.DayPlanDao;
import com.pm2.dao.plan.MasterPlanDao;
import com.pm2.dao.plan.MasterPlanHistoryDao;
import com.pm2.entity.personnel.Developer;
import com.pm2.entity.plan.DayPlan;
import com.pm2.entity.plan.MasterPlan;
import com.pm2.entity.plan.MasterPlanHistory;
import com.pm2.entity.plan.PlanMenu;
import com.pm2.entity.workCalendar.WorkCalendar;
import com.pm2.service.impl.MasterPlanServiceImpl;
import com.shuohe.service.util.sql.EasyuiServiceImpl;
import com.shuohe.util.date.SDate;
import com.shuohe.util.returnBean.ReturnBean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Controller  
@RequestMapping("/pm2/plan/*")  
public class MasterPlanController {

	
	@Autowired
	private MasterPlanDao masterPlanDao; 

	@Autowired
	private MasterPlanHistoryDao masterPlanHistoryDao; 
	
	@Autowired
	private DayPlanDao dayPlanDao; 
	
	@Autowired
	private DeveloperDao developerDao; 
	
	@Autowired
	private WorkCalendarDao workCalendarDao;
	
	@Resource
	private MasterPlanServiceImpl masterPlanService;
	
	@RequestMapping(value="saveMasterPlan.do")  
    public @ResponseBody ReturnBean saveMasterPlan(HttpServletRequest request,HttpServletResponse response){

		Gson reGson = new GsonBuilder()
				.setDateFormat("yyyy-MM-dd")  
				.create();  
		
		String data = request.getParameter("data").replaceAll("\"\"", "null");
		String developer = request.getParameter("developer").replaceAll("\"\"", "null");
		MasterPlan masterPlan = reGson.fromJson(data, new TypeToken<MasterPlan>(){}.getType());
		List<Developer> developerList = reGson.fromJson(developer, new TypeToken<List<Developer>>(){}.getType());

		if(data == null) return new ReturnBean(false,"计划信息不能为空");
		if(developerList==null || developerList.size()==0)  return new ReturnBean(false,"不能没有执行人员");
		if(masterPlan.getPlan_start_date() == null)  return new ReturnBean(false,"不能没有计划起始日期");
		if(masterPlan.getPlan_end_date() == null)  return new ReturnBean(false,"不能没有计划结束日期");
		if(masterPlan.getProject_id() == 0)  return new ReturnBean(false,"不能没有项目");
		if(masterPlan.getProject_stage() == null ||"".equals(masterPlan.getProject_stage()))  return new ReturnBean(false,"项目阶段不能为空");
		
		try
		{
			
			masterPlanDao.updateSortNumberById(masterPlan.getPid(), masterPlan.getSort_number());
			if(null==masterPlan.getTask_level_1()) {
				masterPlan.setTask_level_1_state("1");
			}else {
				masterPlan.setTask_level_1_state("0");
			}
			if(null==masterPlan.getTask_level_2()) {
				masterPlan.setTask_level_2_state("1");
			}else {
				masterPlan.setTask_level_2_state("0");
			}
			if(null==masterPlan.getTask_level_3()) {
				masterPlan.setTask_level_3_state("1");
			}else {
				masterPlan.setTask_level_3_state("0");
			}
			System.out.println(masterPlan);
			masterPlan = masterPlanDao.save(masterPlan);
			
			
			
			List<Date> list = WorkCalendarController.findDates(masterPlan.getPlan_start_date(), masterPlan.getPlan_end_date());
			//先清空旧的日计划
			dayPlanDao.deleteByPid(masterPlan.getId());
			for(int i=0;i<list.size();i++)
			{
				DayPlan dayPlan = new DayPlan();
				dayPlan.setDay(list.get(i));
				dayPlan.setProject_id(masterPlan.getProject_id());
				dayPlan.setPid(masterPlan.getId());
				dayPlanDao.save(dayPlan);
			}
			developerDao.deleteByMasterPlanId(masterPlan.getId());
			
			
			for(int i=0;i<developerList.size();i++)
			{
				Developer d = developerList.get(i);
				d.setMasterplan_id(masterPlan.getId());
				d.setProject_id(masterPlan.getProject_id());
				developerDao.save(d);
			}	
			return new ReturnBean(true,"");
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return new ReturnBean(false,e.getMessage());
		}
	}


	@RequestMapping(value="deleteMasterPlan.do")  
    public @ResponseBody ReturnBean deleteMasterPlan(@RequestParam("id") int id){

		//删除主计划
		//删除主计划相关开发者
		//删除日计划

		try
		{
			masterPlanService.deleteMasterPlan(id);			
			return new ReturnBean(true,"删除成功");
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return new ReturnBean(false,"删除失败");
		}
	}
	
	@RequestMapping(value="changeMasterPlan.do")  
    public @ResponseBody ReturnBean changeMasterPlan(HttpServletRequest request,HttpServletResponse response){

		Gson reGson = new GsonBuilder()
				.setDateFormat("yyyy-MM-dd")  
				.create();  
		
		String data = request.getParameter("data").replaceAll("\"\"", "null");
		String developer = request.getParameter("developer").replaceAll("\"\"", "null");
		MasterPlan masterPlan = reGson.fromJson(data, new TypeToken<MasterPlan>(){}.getType());
		MasterPlanHistory masterPlanHistory = reGson.fromJson(data, new TypeToken<MasterPlanHistory>(){}.getType());
		List<Developer> developerList = reGson.fromJson(developer, new TypeToken<List<Developer>>(){}.getType());

		if(data == null) return new ReturnBean(false,"计划信息不能为空");
		if(developerList==null || developerList.size()==0)  return new ReturnBean(false,"不能没有执行人员");
		if(masterPlan.getPlan_start_date() == null)  return new ReturnBean(false,"不能没有计划起始日期");
		if(masterPlan.getPlan_end_date() == null)  return new ReturnBean(false,"不能没有计划结束日期");
		if(masterPlan.getProject_id() == 0)  return new ReturnBean(false,"不能没有项目");
		if(masterPlan.getProject_stage() == null ||"".equals(masterPlan.getProject_stage()))  return new ReturnBean(false,"项目阶段不能为空");
		
		try
		{
			//保存变更历史
			masterPlanHistoryDao.save(masterPlanHistory);
			
			masterPlanDao.findById(masterPlan.getId());
			if(null==masterPlan.getTask_level_1()) {
				masterPlan.setTask_level_1_state("1");
			}else {
				masterPlan.setTask_level_1_state("0");
			}
			if(null==masterPlan.getTask_level_2()) {
				masterPlan.setTask_level_2_state("1");
			}else {
				masterPlan.setTask_level_2_state("0");
			}
			if(null==masterPlan.getTask_level_3()) {
				masterPlan.setTask_level_3_state("1");
			}else {
				masterPlan.setTask_level_3_state("0");
			}
			System.out.println(masterPlan);
			masterPlan = masterPlanDao.save(masterPlan);
			
			List<Date> list = WorkCalendarController.findDates(masterPlan.getPlan_start_date(), masterPlan.getPlan_end_date());
			//先清空旧的日计划
			dayPlanDao.deleteByPid(masterPlan.getId());
			for(int i=0;i<list.size();i++)
			{
				DayPlan dayPlan = new DayPlan();
				dayPlan.setDay(list.get(i));
				dayPlan.setProject_id(masterPlan.getProject_id());
				dayPlan.setPid(masterPlan.getId());
				dayPlanDao.save(dayPlan);
			}
			//清空旧的执行人
			developerDao.deleteByMasterPlanId(masterPlan.getId());
			for(int i=0;i<developerList.size();i++)
			{
				Developer d = developerList.get(i);
				d.setMasterplan_id(masterPlan.getId());
				d.setProject_id(masterPlan.getProject_id());
				developerDao.save(d);
			}	
			return new ReturnBean(true,"");
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return new ReturnBean(false,e.getMessage());
		}
	}
	
	
	@RequestMapping(value="finish.do")  
    public @ResponseBody ReturnBean finish(@RequestParam("master_plan_id") int master_plan_id
    		,@RequestParam("finish_date") String finish_date,@RequestParam("task_response") String task_response){
		MasterPlan masterPlan = masterPlanDao.findById(master_plan_id);
		if(masterPlan.is_finish() == true)
			return new ReturnBean(false,"完成的任务不能再完成");
		masterPlan.set_finish(true);
		masterPlan.setFinish_date(SDate.praseStringToDate(finish_date));
		masterPlan.setTask_response(task_response);
		masterPlanDao.save(masterPlan);
		return new ReturnBean(true,"任务完成");
	}
	
	@RequestMapping(value="getDayPlanList.do")  
    public @ResponseBody List<Map<String,Object>> getDayPlanList(@RequestParam("project_id") int project_id){
		try
		{
			//1、通过项目找到主计划
			List<MasterPlan> masterPlanList = masterPlanDao.findByProjectId(project_id);

			List<Map<String,Object>> ret = new ArrayList<Map<String,Object>>();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			
			for(MasterPlan masterPlan:masterPlanList)
			{
				Map<String,Object> m = new LinkedHashMap<String,Object>();
	
				m.put("id", masterPlan.getId());
				m.put("project_stage", masterPlan.getProject_stage());
				m.put("plan_content", masterPlan.getPlan_content());
				m.put("task_level_1", masterPlan.getTask_level_1());
				m.put("task_level_2", masterPlan.getTask_level_2());
				m.put("task_level_3", masterPlan.getTask_level_3());
				
				m.put("plan_start_date", sdf.format(masterPlan.getPlan_start_date()));
				m.put("plan_end_date", sdf.format(masterPlan.getPlan_end_date()));
				m.put("plan_manday", masterPlan.getPlan_manday());
				m.put("sort_number",masterPlan.getSort_number());
				
				
				List<Developer> p_list = developerDao.findByMasterPlanId(masterPlan.getId());
				String users = "";
				for(int x=0;x<p_list.size();x++)
				{
					users+=p_list.get(x).getName()+"   ";
				}
				m.put("developer", users);
				
				//2、通过主计划找到工作日
				List<DayPlan> dayPlanList = dayPlanDao.findByPid(masterPlan.getId());
				for(DayPlan dayPlan:dayPlanList)
				{
					m.put(sdf.format(dayPlan.getDay()), 1);
				}
				
				//获得整个项目的开始时间和结束时间
				Date end_date = masterPlanDao.findMaxEndDateByProjectId(project_id);
				Date start_date = masterPlanDao.findMinStartDateByProjectId(project_id);
				//将所有间隔时间的周末和假日检索出来
				List<WorkCalendar> workCalendar_list= workCalendarDao.findByStardAndEndDate(start_date, end_date);
				//将周末和假日也放入返回数据中
				for(WorkCalendar w:workCalendar_list)
				{
					if(w.is_holiday())
						m.put(sdf.format(w.getDay_date()), "holiday");
					if(w.is_weekend())
						m.put(sdf.format(w.getDay_date()), "weeked");
				}				
				ret.add(m);
			}
			return ret;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
	
	
	@RequestMapping(value="getDayListByPlan.do")  
	public @ResponseBody List<List<Map<String,Object>>> getDayList(@RequestParam("project_id") int project_id) {
		//1、获取项目计划的起始时间和结束时间
		Date end_date = masterPlanDao.findMaxEndDateByProjectId(project_id);
		Date start_date = masterPlanDao.findMinStartDateByProjectId(project_id);
		if(end_date == null || start_date==null) return null;
		
		//2、输出起始时间和结束时间的表头
		List<Date> date_list = WorkCalendarController.findDates(start_date, end_date);
		
		List<Map<String,Object>> day_columns_list = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> month_columns_list = new ArrayList<Map<String,Object>>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		Calendar min = Calendar.getInstance();
	    Calendar max = Calendar.getInstance();
	 
	    min.setTime(start_date);
	    min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH)-1, 1);
	 
	    max.setTime(end_date);
	    max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH)-1, 2);

		Calendar curr = min;
		while (curr.before(max)) {
			curr.add(Calendar.MONTH, 1);
			Map<String,Object> cm = new LinkedHashMap<String,Object>();
			cm.put("title", curr.get(Calendar.MONTH)+1+"月份");
			cm.put("colspan", curr.getActualMaximum(Calendar.DAY_OF_MONTH));
			month_columns_list.add(cm);
			System.out.println(curr.getTime().toLocaleString());
			int maxDay = curr.getActualMaximum(Calendar.DAY_OF_MONTH);
			System.out.println("Max Day: " + maxDay);
			
			int minDay = curr.getActualMinimum(Calendar.DAY_OF_MONTH);
			System.out.println("Min Day: " + minDay);
			Calendar curr_xxx = Calendar.getInstance();
			
			for (int i = minDay; i <= maxDay; i++) {
				curr_xxx.set(curr.get(Calendar.YEAR), curr.get(Calendar.MONTH), i);
				System.out.println("Day: " + curr_xxx.getTime().toLocaleString());
				
				Map<String,Object> c = new LinkedHashMap<String,Object>();
				c.put("field", sdf.format(curr_xxx.getTime()));
//				c.put("title", curr_xxx.getActualMaximum(Calendar.DAY_OF_MONTH)+"");
				c.put("title", curr_xxx.get(Calendar.DAY_OF_MONTH)+"");
//				c.put("formatter", "dealfunction()");
				c.put("width", 35);
				c.put("rowspan", 1);
				day_columns_list.add(c);	
			}

		}
		
		List<List<Map<String,Object>>> ret = new ArrayList<List<Map<String,Object>>>();
		if(month_columns_list.size()!=0)
			ret.add(month_columns_list);
		if(day_columns_list.size()!=0)
			ret.add(day_columns_list);
		return ret;
	}
	
	@RequestMapping(value="upMove.do")  
	public @ResponseBody ReturnBean upMove(@RequestParam("id") int id) {
		MasterPlan masterPlan = masterPlanDao.findById(id);
		masterPlanDao.updateSortNumberById(masterPlan.getPid(), masterPlan.getSort_number());
		return new ReturnBean(true,"上移成功");
	}
	@RequestMapping(value="downMove.do")  
	public @ResponseBody ReturnBean downMove(@RequestParam("id") int id) {
		MasterPlan masterPlan = masterPlanDao.findById(id);
		masterPlanDao.updateSortNumberById(masterPlan.getPid(), masterPlan.getSort_number());
		return new ReturnBean(true,"下移成功");
	}
	/**
	 * 获取项目对应的计划，拼接为树形菜单
	 * @param projectId
	 * @return
	 */
	@RequestMapping(value="getTaskPlanTree.do")  
	public @ResponseBody List<PlanMenu> getTaskPlanTree(HttpServletRequest request) {
		String str = request.getParameter("projectId");
		return masterPlanService.findByProjectId(Integer.parseInt(str));
		
	}

	
}
